#include "ota_http_curl.h"
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>

/**
 * @brief  把远端数据装配在结构中
 */
static size_t curl_getStringFromHttp(void *data, size_t size, size_t nmemb, void *userp)
{
    response_body_t *response_body = (response_body_t *)userp;
    int data_len = size * nmemb;
    response_body->str =  malloc(data_len + 1);
    response_body->str_len =data_len  ;
    memcpy(response_body->str, data, data_len);

    response_body->str[data_len]='\0';

    return data_len;
}

/**
 * @brief 从http服务获取字符串内容
 */
response_body_t  *ota_http_curl_get_string(char *url)
{
    // 利用curl 访问http服务
    //1 初始化curl 句柄 
    CURL *curl = curl_easy_init(); 
    if(curl == NULL)
    {
        perror("curl_easy_init() failed");
        return NULL;
    }
    //2 设置curl句柄  //1 地址 //2 接收数据的回调函数 //3 接收数据容器
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_getStringFromHttp);

    response_body_t  *response_body=malloc(sizeof(response_body_t));
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_body);
    //3 执行访问
   CURLcode code= curl_easy_perform(curl);
   if(code != CURLE_OK)
   {
       // free(response_body->str);
        free(response_body);
        curl_easy_cleanup(curl);
       perror("curl_easy_perform() failed");
       return NULL;
   }
    curl_easy_cleanup(curl);
    //4 返回结果
    return  response_body;
}


/**
 * @brief 从http服务获取字符串内容
 */
int  ota_http_curl_downloadFile(char *url,char *file_name_path)
{
    // 利用curl 访问http服务
    //1 初始化curl 句柄 
    CURL *curl = curl_easy_init(); 
    if(curl == NULL)
    {
        perror("curl_easy_init() failed");
        return -1;
    }
    //2 设置curl句柄  //1 地址 //2 接收数据的回调函数 //3 接收数据容器
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite  );

    FILE *fp = fopen(file_name_path, "wb");
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    //3 执行访问
   CURLcode code= curl_easy_perform(curl);
   if(code != CURLE_OK)
   {
       // free(response_body->str);
         fclose(fp);
         curl_easy_cleanup(curl);
        perror("curl_easy_perform() failed");
        return -1;
   }
    curl_easy_cleanup(curl);
    //4 返回结果
    fclose(fp);  //如果不close ，很有可能文件不完整

    return   0;
}

int ota_http_download(char *url, char *file_path)
{
    //1  初始化一个curl 
   CURL *curl = curl_easy_init();
   if (curl==NULL)
   {
          perror("curl_easy_init error");
          return -1;
   }
   //2  给curl 设置参数 1  url  2  接收数据的回调函数  3 接收数据的容器
   curl_easy_setopt(curl, CURLOPT_URL, url);
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);

   FILE *file= fopen(file_path,"wb");
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
   //3  执行curl 
    
  CURLcode res= curl_easy_perform(curl);
  if (res != CURLE_OK)
  {
      perror("curl_easy_perform error");
      return -1;
  }
      
  //4  释放资源curl 
  curl_easy_cleanup(curl);
  fclose(file); //重要
  
  //5 返回响应体
     return 0;
}
